<template>
  <div id="goods">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 注意 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-row>
        <span>选择商品分类：</span>
        <!-- 级联选择器 -->
        <el-cascader
          v-model="selectValue"
          :options="getParams"
          :props="paramsProps"
          @change="handleChange"
        ></el-cascader>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" type="border-card" @tab-click="tabsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="comFlag"
            class="addBtn"
            @click="addParamsVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyData" style="width: 100%" stripe border>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引号 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="min"
                  type="primary"
                  icon="el-icon-edit"
                  class="btns"
                  @click="editorName(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="min"
                  type="danger"
                  icon="el-icon-delete"
                  class="btns"
                  @click="deleForm(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="comFlag"
            class="addBtn"
            @click="addParamsVisible = true"
            >添加属性</el-button
          >
          <!-- 静态参数表格 -->
          <el-table :data="onlyData" style="width: 100%" stripe border>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引号 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  size="min"
                  type="primary"
                  icon="el-icon-edit"
                  class="btns"
                  @click="editorName(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="min"
                  type="danger"
                  icon="el-icon-delete"
                  class="btns"
                  @click="deleForm(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 两个公用一个对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addParamsVisible"
      width="50%"
      @close="addParamsForm"
    >
      <el-form
        ref="addRef"
        :rules="addRules"
        :model="addForm"
        label-width="80px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editorParamsVisible"
      width="50%"
      @close="editorParamsForm"
    >
      <el-form
        ref="editorRef"
        :rules="editorRules"
        :model="editorForm"
        label-width="80px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editorForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editorParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="editorParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'params',
  data() {
    return {
      // 存储所有商品分类数据
      getParams: [],
      // 级联选择器
      paramsProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // 级联选择器双向绑定值
      selectValue: [],
      activeName: 'many',
      // 动态参数数据
      manyData: [],
      // 静态参数数据
      onlyData: [],
      // 对话框
      addParamsVisible: false,
      // 添加参数
      addForm: {
        attr_name: '',
      },
      // 表单验证
      addRules: {
        attr_name: [
          { required: true, message: '参数名不能为空', trigger: 'blur' },
        ],
      },
      // 编辑对话框
      editorParamsVisible: false,
      // 编辑参数
      editorForm: {
        attr_name: '',
      },
      // 表单验证
      editorRules: {
        attr_name: [
          { required: true, message: '参数名不能为空', trigger: 'blur' },
        ],
      },
      // 参数表给显示与隐藏
    }
  },
  created() {
    this.getParamsList()
  },
  methods: {
    // 获取所有的商品分类列表
    async getParamsList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.getParams = res.data
      // console.log(this.getParams)
    },
    // 级联选择器监听
    handleChange() {
      if (this.selectValue.length !== 3) {
        ;(this.selectValue = []), (this.manyData = []), (this.onlyData = [])
        this.$message.warning('只允许为第三级分类设置参数')
        return
      }
      // 如果等于3，调用
      this.getParamsData()
    },
    // tabs标签页
    tabsClick() {
      // 调用
      this.getParamsData()
      // console.log(this.activeName);
    },
    // 获取分类参数列表
    async getParamsData() {
      // 选中三级分类
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName,
          },
        }
      )
      if (res.meta.status !== 200) return
      // console.log(res.data)
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        // 动态参数数据
        this.manyData = res.data
      } else {
        // 静态参数数据
        this.onlyData = res.data
      }
      console.log(res.data)
    },
    // 监听添加对话框
    addParamsForm() {
      this.$refs.addRef.resetFields()
    },
    // 确定添加
    addParams() {
      this.$refs.addRef.validate(async (vail) => {
        if (!vail) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201) return
        this.$message.success(res.meta.msg)
        this.getParamsData()
        this.addParamsVisible = false
        // console.log(res);
      })
    },
    // 编辑对话框
    async editorName(getInfo) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${getInfo.attr_id}`,
        {
          attr_sel: getInfo.attr_sel,
        }
      )
      if (res.meta.status !== 200) return
      this.editorForm = res.data
      this.editorParamsVisible = true
      console.log(this.editorForm)
      // console.log(getInfo);
    },
    // 监听编辑对话框
    editorParamsForm() {
      this.$refs.editorRef.resetFields()
    },
    // 点击确定编辑
    editorParams() {
      this.$refs.editorRef.validate(async (vail) => {
        if (!vail) return this.$message.error('表单验证失败')
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editorForm.attr_id}`,
          {
            attr_name: this.editorForm.attr_name,
            attr_sel: this.editorForm.attr_sel,
          }
        )
        if (res.meta.status !== 200) return
        this.$message.success('动态数据修改成功')
        // 渲染分类数据的列表
        this.getParamsData()
        this.editorParamsVisible = false
      })
    },
    // 删除操作
    deleForm(attr_id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${attr_id}`
          )
          if (res.meta.status !== 200) return this.$message.error('删除失败')
          this.$message.success('删除成功')
          this.getParamsData()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 展开行
    showInput(row) {
      row.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length == 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      if (row.inputValue) {
        row.attr_vals.push(row.inputValue.trim())
      }
      row.inputVisible = false
      row.inputValue = ''
      // 调用
      this.selectComm(row)
    },
    // 添加和删除公用
    async selectComm(row) {
      // 需要保存到数据库中
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )
      if (res.meta.status !== 200) return
      this.$message.success('添加成功')
    },
    async handleClose(index, row) {
      row.attr_vals.splice(index, 1)
      // 调用
      this.selectComm(row)
    },
  },
  computed: {
    comFlag() {
      if (this.selectValue.length !== 3) {
        return true
      }
      return false
    },
    cateId() {
      if (this.selectValue.length === 3) {
        // 证明选择的是三级分类,返回分类id
        return this.selectValue[2]
      }
    },
    // 对话框
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    },
  },
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
  border: 1px solid #ebeef5;
  background-color: #fff;
  color: #303133;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: none;
}
.el-card.is-always-shadow {
  box-shadow: none;
}
.el-alert {
  background-color: #e6a23c !important;
  color: #fff !important;
}
.el-row {
  margin: 20px 0;
}
.addBtn {
  font-size: 12px;
  padding: 7px 15px;
}
.btns {
  padding: 7px 15px;
  font-size: 12px;
}
.el-tag:first-child {
  margin-left: 48px;
}
.el-tag {
  margin-left: 15px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>